﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Desktop.Controls
{
    /// <summary>
    /// Interaction logic for WorkspaceTabItem.xaml
    /// </summary>
    public partial class WorkspaceTabItem : TabItem
    {
        #region Events

        public static readonly RoutedEvent CloseTabEvent =
            EventManager.RegisterRoutedEvent("CloseTab", RoutingStrategy.Bubble,
                typeof(RoutedEventHandler), typeof(WorkspaceTabItem));

        public event RoutedEventHandler CloseTab
        {
            add
            {
                AddHandler(CloseTabEvent, value);
            }
            remove
            {
                RemoveHandler(CloseTabEvent, value);
            }
        }

        #endregion

        #region Variables

        private Button _closeButton;
        private bool _isCloseable;

        #endregion

        #region Constructors

        static WorkspaceTabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WorkspaceTabItem), new FrameworkPropertyMetadata(typeof(WorkspaceTabItem)));
        }

        #endregion

        #region Properties

        public bool IsCloseable
        {
            get
            {
                return _isCloseable;
            }
            set
            {
                _isCloseable = value;
                if (_closeButton != null)
                {
                    _closeButton.Visibility = _isCloseable ? Visibility.Visible : Visibility.Hidden;
                }
            }
        }

        #endregion

        #region Methods

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            
            _closeButton = GetTemplateChild("PART_Close") as Button;

            if (_closeButton != null)
            {
                _closeButton.Click += new RoutedEventHandler(CloseButton_Click);
            }
        }

        #endregion

        #region Event Handlers

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs(CloseTabEvent, this));
        }

        #endregion
    }
}